package com.mall.shopping.services;

import com.mall.commons.result.AbstractResponse;
import com.mall.commons.tool.exception.ExceptionUtil;
import com.mall.shopping.CartShopService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.converter.CartItemConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dto.*;
import com.mall.shopping.utils.ExceptionProcessorUtils;
import com.mall.shopping.utils.ResponseProcessUtils;
import org.apache.dubbo.config.annotation.Service;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;

import javax.xml.bind.ValidationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: 逍遥子
 * @Date: 2022/01/19/23:24
 * @Description:
 */
@Service
public class CartShopServiceImpl implements CartShopService {

    // @Autowired
    // IDeleteCartShopMapper deleteCartShopMapper;

    /*private static RedissonClient redissonClient;

    static {

        // Redis
        Config config = new Config();
        config.useSingleServer().setAddress("redis://localhost:6379");
        // 创建Redis客户端
        redissonClient = Redisson.create(config);
    }*/

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    ItemMapper itemMapper;

    // 购物车列表
    @Override
    public CartListByIdResponse getCartListById(CartListByIdRequest request) {
        // 1.创建响应对象
        CartListByIdResponse response = new CartListByIdResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.获取用户购物车数据
            Map<Long, CartProductDto> map = redissonClient.getMap(request.getUserId().toString());

            // 遍历map集合, 存放到List集合
            ArrayList<CartProductDto> cartProductDtos = new ArrayList<>();

            Iterator<Map.Entry<Long, CartProductDto>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                // 获取商品信息
                Map.Entry<Long, CartProductDto> item = iterator.next();
                // 放入List集合
                cartProductDtos.add(item.getValue());
            }
            // 4.封装数据
            response.setCartProductDtos(cartProductDtos);
            // 5.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    // 添加商品到购物车
    @Override
    public AddCartResponse addToCart(AddCartRequest request) {
        // 1.创建响应对象
        AddCartResponse response = new AddCartResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.获取用户购物车数据
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 判断购物车是否已经有该商品信息
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            boolean flag = map.containsKey(itemId);
            if (flag) {
                System.out.println("已有该商品信息...");
                // 购物车已经存在该商品信息, 更新购物车中商品数量
                System.out.println(map.get(itemId).getProductNum() + num);
                CartShopDto cartShopDto = map.get(itemId);
                Long oldNum = cartShopDto.getProductNum();
                cartShopDto.setProductNum(oldNum + num);
                map.put(itemId, cartShopDto);
            } else {
                // 4.从数据库中查询商品信息, 添加到购物车
                Item item = itemMapper.selectByPrimaryKey(request.getItemId());
                // 类型转换, (这里由于遗留问题, 多定义了一个购物车商品信息类, CartShopDto 与 CartProductDto类完全一样)
                CartShopDto cartShopDto = CartItemConverter.itemCartShop2Dto(item);
                cartShopDto.setProductNum(Long.parseLong(num + ""));
                System.out.println(cartShopDto);
                map.put(itemId, cartShopDto);
            }
            // 5.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    // 更新购物车中的商品
    @Override
    public UpdateCartNumResponse updateCartNum(UpdateCartNumRequest request) {
        // 1.创建响应对象
        UpdateCartNumResponse response = new UpdateCartNumResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.获取用户购物车数据
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 判断购物车是否已经有该商品信息
            Long itemId = request.getItemId();
            Integer num = request.getNum();
            String checked = request.getChecked();
            boolean flag = map.containsKey(itemId);
            if (flag) {
                System.out.println(checked);
                System.out.println("已有该商品信息...");
                // 购物车已经存在该商品信息, 更新购物车中商品信息, 这里是覆盖, 不是叠加
                CartShopDto cartShopDto = map.get(itemId);
                cartShopDto.setProductNum(Long.parseLong(num + ""));
                System.out.println(Boolean.parseBoolean(checked));
                cartShopDto.setChecked(Boolean.parseBoolean(checked));
                System.out.println(cartShopDto);
                map.put(itemId, cartShopDto);
            } else {
                // 4.说明购物车中没有该商品
                response.setMsg("非正常请求...购物车中没有该商品信息...");
            }
            // 5.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    // 删除购物车商品
    @Override
    public DeleteCartShopResponse deleteCartShop(DeleteCartShopRequest request) {

        // 1.创建响应对象
        DeleteCartShopResponse deleteCartShopResponse = new DeleteCartShopResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.执行SQL语句
            // int affectRow = deleteCartShopMapper.deleteCartShop(request.getUserId(), request.getProductId());
            // 这里采用了Redis数据库来存储用户购物车中的商品, 所以直接操作Redis数据库缓存的用户购物车数据
            // 获取用户购物车数据
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 删除用户购物车商品
            map.remove(request.getProductId());
            // 4.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(deleteCartShopResponse);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteCartShopResponse, e);
        }
        return deleteCartShopResponse;
    }

    // 删除购物车选中的商品
    @Override
    public DeleteCartShopOfSelectedResponse deleteCartShopOfSelected(DeleteCartShopOfSelectedRequest request) {
        // 1.创建响应对象
        DeleteCartShopOfSelectedResponse deleteCartShopOfSelectedResponse = new DeleteCartShopOfSelectedResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 获取用户购物车数据
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 3.遍历集合, 删除购物车中选中的商品
            Iterator<Map.Entry<Long, CartShopDto>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, CartShopDto> next = iterator.next();
                // 删除购物车选中的商品
                if (next.getValue().isChecked()) {
                    map.remove(next.getKey());
                }
            }
            // 4.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(deleteCartShopOfSelectedResponse);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteCartShopOfSelectedResponse, e);
        }
        return deleteCartShopOfSelectedResponse;
    }

    // 全选/全不选购物车商品
    @Override
    public SelectCartShopResponse selectCartShop(SelectCartShopRequest request) {
        // 1.创建响应对象
        SelectCartShopResponse selectCartShopResponse = new SelectCartShopResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.获取用户购物车数据
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 遍历集合, 全选/全不选购物车商品
            // 是否选中商品
            boolean checked = request.isChecked();
            System.out.println(checked);
            Iterator<Map.Entry<Long, CartShopDto>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, CartShopDto> shopItem = iterator.next();
                Long productId = shopItem.getKey();
                CartShopDto cartShopDto = shopItem.getValue();
                cartShopDto.setChecked(checked);
                map.put(productId, cartShopDto);
            }
            // 4.执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(selectCartShopResponse);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(selectCartShopResponse, e);
        }
        return selectCartShopResponse;
    }

    // 清空购物车
    @Override
    public ClearCartItemResponse clearCartItemByUserID(ClearCartItemRequest request) {
        // 1.创建响应对象
        ClearCartItemResponse response = new ClearCartItemResponse();
        try {
            // 2.参数校验
            request.requestCheck();
            // 3.获取用户购物车
            Map<Long, CartShopDto> map = redissonClient.getMap(request.getUserId().toString());
            // 4.清空购物车
            Iterator<Map.Entry<Long, CartShopDto>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Long, CartShopDto> shopItem = iterator.next();
                map.remove(shopItem.getKey());
            }
            // 执行成功
            ResponseProcessUtils.wrapperHandlerSuccessResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }
}
